/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Feb 29, 2012  2:14:17 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : apps.promis.in.construction
 * File Name : PurchaseOrderAction.java
 * TODO
 */
package apps.promis.in.construction;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import jpa.entitys.promis.common.Company;
import jpa.entitys.promis.common.CostProject;
import jpa.entitys.promis.common.CostProjectArticle;
import jpa.entitys.promis.common.CostProjectArticlePK;
import jpa.entitys.promis.common.TaxType;
import jpa.entitys.promis.common.UmMaster;
import jpa.entitys.promis.construction.PurchaseOrder;
import jpa.entitys.promis.construction.PurchaseOrderBudget;
import jpa.entitys.promis.construction.PurchaseOrderBudgetPK;
import jpa.entitys.promis.construction.PurchaseOrderItem;
import jpa.entitys.promis.construction.PurchaseOrderItemPK;
import jpa.entitys.promis.construction.PurchaseOrderPK;
import jpa.entitys.promis.construction.PurchaseRequestBudget;
import jpa.entitys.promis.construction.PurchaseRequestBudgetPK;
import jpa.entitys.promis.construction.PurchaseRequestItem;
import jpa.entitys.promis.construction.PurchaseRequestItemPK;
import jpa.entitys.promis.construction.SyncPr;
import jpa.entitys.promis.construction.SyncPrBudget;
import jpa.entitys.promis.construction.SyncPrItem;
import jpa.entitys.synchro.staging.MmPurchaseOrder;
import jpa.service.promis.common.CompanyServices;
import jpa.service.promis.common.CostProjectArticleServices;
import jpa.service.promis.common.ProjectServices;
import jpa.service.promis.common.TaxTypeServices;
import jpa.service.promis.common.UmMasterServices;
import jpa.service.promis.construction.PurchaseOrderBudgetServices;
import jpa.service.promis.construction.PurchaseOrderItemServices;
import jpa.service.promis.construction.PurchaseOrderServices;
import jpa.service.promis.construction.PurchaseRequestBudgetServices;
import jpa.service.promis.construction.PurchaseRequestItemServices;
import jpa.service.promis.construction.SyncPrBudgetServices;
import jpa.service.promis.construction.SyncPrItemServices;
import jpa.service.promis.construction.SyncPrServices;
import jpa.service.synchro.staging.MmPurchaseOrderServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import promis.utility.Utilitys;
import apps.sessionFactory;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Nov 13, 2013 : 2:24:29 PM 
 * CreateBy=Chatree Siangklom
 * 
 * PurchaseOrderAction
 * TODO
 */
public class PurchaseOrderAction {
	
	private static final Logger log = Logger.getLogger(PurchaseOrderAction.class);	
	private EntityManager  EmPromis;
	private EntityManager  EmSynchro;
	
	/**
	 * Date =Nov 13, 2013 : 2:24:39 PM 
	 * CreateBy=Chatree Siangklom
	 * PurchaseOrderAction
	 * TODO
	 * @throws Exception
	 */
	public PurchaseOrderAction() throws Exception {
		EmPromis = sessionFactory.CreateEmPromis();
		EmSynchro = sessionFactory.CreateEmSynchro();
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:24:44 PM 
	 * CreateBy=Chatree Siangklom
	 * List<String>
	 * TODO
	 * @return
	 * @throws Exception
	 */
	private List<String> GroupSAPPoDoc() throws Exception {
		MmPurchaseOrderServices mmPurchaseOrderServ = new MmPurchaseOrderServices(EmSynchro);		
		List<MmPurchaseOrder> lst = mmPurchaseOrderServ.findAllIsSync("N");
		
		HashMap<String, String> mapVal = new HashMap<String, String>();
		if(!CommonService.IsNull(lst)){
			for(MmPurchaseOrder model : lst)
			{
				if(model.getExtRefNo() != null)
					mapVal.put(model.getExtRefNo(), model.getExtRefNo());
			}
		}		 
		
		List<String> sapdocNo = new ArrayList<String>();
		if(!mapVal.isEmpty())
		{
			List<MmPurchaseOrder> promis_lst = new ArrayList<MmPurchaseOrder>(); 
			Set set = mapVal.entrySet();
			Iterator i = set.iterator();
			while(i.hasNext())
			{
				Map.Entry me = (Map.Entry)i.next();
				sapdocNo.add(me.getValue().toString());				
			}
		}
		return sapdocNo;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 10:36:01 AM 
	 * CreateBy=Chatree Siangklom
	 * List<MmPurchaseOrder>
	 * TODO
	 * @param issync
	 * @param instanceNo
	 * @param extRefNo
	 * @param poStatus
	 * @return
	 * @throws Exception
	 */
	private List<MmPurchaseOrder> findSapPoDoc(String issync, String instanceNo, String extRefNo, String poStatus) throws Exception {
		MmPurchaseOrderServices mmPurchaseOrderServ = new MmPurchaseOrderServices(EmSynchro);		
		return mmPurchaseOrderServ.findSapPoDoc(issync, instanceNo, extRefNo, poStatus);
	}	
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 10:35:58 AM 
	 * CreateBy=Chatree Siangklom
	 * boolean
	 * TODO
	 * @param sap_po_doc_no
	 * @return
	 * @throws Exception
	 */
	private boolean CheckExist(String sap_po_doc_no) throws Exception {
		try{
			
			PurchaseOrderServices PurchaseOrderServ = new PurchaseOrderServices(EmPromis);
			List<PurchaseOrder> lstPo = PurchaseOrderServ.findBySapPoNo1(sap_po_doc_no);
			
			return (CommonService.getSize(lstPo) > 0) ? true : false;
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.out.println(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * @ A = Active, Z=Cancel, C = Closed
	 * @param mmPurchaseOrder
	 * @throws Exception
	 */
	private boolean CanclePo(List<MmPurchaseOrder> MmPurchaseOrder_lst) throws Exception {
		
		PurchaseOrderServices purchaseOrderServ = new PurchaseOrderServices(EmPromis);
		MmPurchaseOrderServices mmPurchaseOrderServ = new MmPurchaseOrderServices(EmSynchro);
		MmPurchaseOrder mmPurchaseOrder;
		
		try{
			if(!CommonService.IsNull(MmPurchaseOrder_lst))
			{
				mmPurchaseOrder = MmPurchaseOrder_lst.get(0);
				if(CommonService.IsNullRString(mmPurchaseOrder.getPoStatus()).equals("Z"))
				{
					//Search old Promis PO
					List<PurchaseOrder> model_lst = purchaseOrderServ.findBySapPoNo1(mmPurchaseOrder.getExtRefNo());
					if(!CommonService.IsNull(model_lst)){
						if(CommonService.getSize(model_lst) == 1){
							
							PurchaseOrder model = model_lst.get(0);
							if(model != null)
							{
								if(model.getStatus().equals("C"))
									throw new Exception("Purchase Order : " + model.getSyncExternalRefNo() + " Currently is Closed.");
								
								Double received_qty = 	purchaseOrderServ.CheckPoReceived(model.getId());
														System.out.println("CHECK_PO_RECEIVED : " + received_qty);
														
								if(received_qty <= 0)
								{
									model.setStatus("Z");
									purchaseOrderServ.Updated(model);
									List<MmPurchaseOrder> poSyncLst = new ArrayList<MmPurchaseOrder>();
									for(MmPurchaseOrder mmPurchase : MmPurchaseOrder_lst)
									{
										mmPurchase.setRetuPmsPoCompany(model.getId().getCompany());
										mmPurchase.setRetuPmsPoProject(model.getId().getProject());
										mmPurchase.setRetuPmsPoType(model.getId().getPoType());
										mmPurchase.setRetuPmsPoSeries(model.getId().getPoSeries());
										mmPurchase.setRetuPmsPoNo(model.getId().getPoNo());
										mmPurchase.setRetuPmsPoRevisionNo(model.getId().getRevisionNo());							
										mmPurchase.setRetuPmsPoPoDocNo( CommonService.IsNullRString(model.getId().getPoType()) + "-" 
																	  + CommonService.IsNullRString(model.getId().getPoSeries()) + "-" 
																	  + Utilitys.leftPad(CommonService.IsNullRString(model.getId().getPoNo()), 6, "0") + "-" 
																	  + CommonService.IsNullRString(model.getId().getRevisionNo()));
										
										
										mmPurchase.setIssync("Y");
										mmPurchase.setMsgCode("S");
										mmPurchase.setMsgDesc("Success");
										mmPurchase.setMsgActResult(null);
										poSyncLst.add(mmPurchase);
									}
									new MmPurchaseOrderServices(EmSynchro).Updated(poSyncLst);
									return true;
								}else{
									System.out.println("Error Can't Cancel Purchase Order SAP DOC NO : " + mmPurchaseOrder.getExtRefNo() + "//TOT Received Qty : " + received_qty);
									throw new Exception("Error Can't Cancel Purchase Order SAP DOC NO : " + mmPurchaseOrder.getExtRefNo() + "//TOT Received Qty : " + received_qty);
								}
							}
						}else{
							System.out.println("Error PROMIS Purchase Order More records  SAP DOC NO : " + mmPurchaseOrder.getExtRefNo());
							throw new Exception("Error PROMIS Purchase Order More records  SAP DOC NO : " + mmPurchaseOrder.getExtRefNo());	
						}
					}else{
						System.out.println("Error find not found  [SAP DOC NO : " + mmPurchaseOrder.getExtRefNo() + "]");
						throw new Exception("Error find not found [SAP DOC NO : " + mmPurchaseOrder.getExtRefNo() + "]");
					}
				}
			}else
			{
				System.out.println("Error MmPurchaseOrder in Staging is null");
				throw new Exception("Error MmPurchaseOrder in Staging is null");	
			}				
		}catch(Exception ex)
		{
			List<MmPurchaseOrder> poSyncLst = new ArrayList<MmPurchaseOrder>();
			if(!CommonService.IsNull(MmPurchaseOrder_lst)){
				for(MmPurchaseOrder mmPurchase : MmPurchaseOrder_lst)
				{
					mmPurchase.setIssync("Y");
					mmPurchase.setMsgCode("E");
					mmPurchase.setMsgDesc(CommonService.CutString(ex.getMessage(), 3500));
					mmPurchase.setMsgActResult(CommonService.CutString(ex.getMessage(), 3500));				
					mmPurchase.setMsgActResult(null);
					poSyncLst.add(mmPurchase);
				}
				mmPurchaseOrderServ.Updated(poSyncLst);
			}
			
			System.out.println(ex.getMessage());
			log.error(ex.getMessage());
			throw ex;
		}
		return false;		
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:23 PM 
	 * CreateBy=Chatree Siangklom
	 * Company
	 * TODO
	 * @param sapCompanyCode
	 * @return
	 * @throws Exception
	 */
	private Company getCompanyBySapCode(String sapCompanyCode) throws Exception {
		return new CompanyServices(EmPromis).findBySapCompany(sapCompanyCode);
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:26 PM 
	 * CreateBy=Chatree Siangklom
	 * CostProject
	 * TODO
	 * @param sap_plant_code
	 * @return
	 * @throws Exception
	 */
	private CostProject getProjectByPlantCode(String sap_plant_code) throws Exception
	{
		return new ProjectServices(EmPromis).findByPlantCode(sap_plant_code);
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:30 PM 
	 * CreateBy=Chatree Siangklom
	 * String
	 * TODO
	 * @param po_type
	 * @return
	 * @throws Exception
	 */
	private String ConvertPoType(String po_type) throws  Exception {
		String temp_po_type = "";
		if(!CommonService.IsNull(po_type)){
			if(po_type.equals("C") || po_type.equals("S"))
				temp_po_type = "PO";
			else if(po_type.equals("P"))
				temp_po_type = "PO";
			else if(po_type.equals("A"))
				temp_po_type = "PU";
			else if(po_type.equals("M"))
				temp_po_type = "PU";
			else
				throw new Exception("Can't Map Type of purchase=("+ po_type +")");
		}
		return temp_po_type;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:34 PM 
	 * CreateBy=Chatree Siangklom
	 * String
	 * TODO
	 * @param value0
	 * @param value1
	 * @param value2
	 * @param value3
	 * @param value4
	 * @param value5
	 * @param value6
	 * @return
	 * @throws Exception
	 */
	private String DocumentConCat(Object value0, Object value1, Object value2, Object value3, Object value4, Object value5, Object value6) throws Exception {
		String temp = "";
		temp += CommonService.IsNullRString(value0) + "-";
		temp += "-" + CommonService.IsNullRString(value1);
		temp += "-" + CommonService.IsNullRString(value2);
		temp += "-" + CommonService.IsNullRString(value3);
		temp += "-" + CommonService.IsNullRString(value4);
		temp += "-" + CommonService.IsNullRString(value5);
		temp += "-" + CommonService.IsNullRString(value6);
		
		return temp;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:36 PM 
	 * CreateBy=Chatree Siangklom
	 * PurchaseOrder
	 * TODO
	 * @param mmPurchase
	 * @return
	 * @throws Exception
	 */
	private PurchaseOrder setHeader(MmPurchaseOrder mmPurchase) throws Exception 
	{
		try{
			
			//Company company = getCompanyBySapCode(mmPurchase.getSapCompanyCode());
			CostProject project = getProjectByPlantCode(mmPurchase.getSapPlantCode());
			if(project != null)
			{				
				PurchaseOrderServices PurchaseOrderServ = new PurchaseOrderServices(EmPromis);
				PurchaseOrder model = null;
				//*****************************************************************************************				
				List<PurchaseOrder> po_list = PurchaseOrderServ.findBySapPoNo1(mmPurchase.getExtRefNo());
				if(CommonService.getSize(po_list) > 0){
					if(CommonService.getSize(po_list) == 1){
						//Edit PO						
						if(CommonService.IsNullRString(po_list.get(0).getStatus()).equals("A")){
							model = po_list.get(0);
						}else{
							model = null;
							throw new Exception("ERROR PO NO :" + po_list.get(0).getSyncExternalRefNo() + "//currently status : " + po_list.get(0).getStatus());
						}
					}else
					{
						model = null;
						String po_str = "";
						for(PurchaseOrder po : po_list)
							po_str += "// " + DocumentConCat(po.getId().getCompany(), po.getId().getProject(), po.getId().getPoType(), po.getId().getPoSeries(), po.getId().getPoNo(), po.getId().getRevisionNo(), ""); 
							
						throw new Exception("ERROR PROMIS have more(s) than one Rec. PO Size = " + po_list.size() + " PO NO = " + po_str);
					}
				}else{
					//Create New PO
					model = new PurchaseOrder();
					String series_no = PurchaseOrderServ.getPromisSeriesNext(project.getId().getCompany(), project.getId().getProject(), ConvertPoType(mmPurchase.getPoType()), CommonService.ConvertPmsStagingDateTime(mmPurchase.getPoDate()));					
					log.info("series_no : " + series_no);
					
					if(CommonService.IsNull(series_no)) 
						throw new Exception("Error can not defind series no");
					
					Long document_no = PurchaseOrderServ.getPromisDocumentNoNext(project.getId().getCompany(), project.getId().getProject(), ConvertPoType(mmPurchase.getPoType()), series_no);
					log.info("document_no : " + document_no);
					
					if(document_no <= 0)
						throw new Exception("Error can not generate next Document No FN:GEN_DOCUMENT_NO (company="+ project.getId().getCompany() +",series="+ series_no +",type="+ ConvertPoType(mmPurchase.getPoType()) +",project="+ project.getId().getProject() +")");
					
					PurchaseOrderPK id = new PurchaseOrderPK();
					id.setCompany(project.getId().getCompany());
					id.setProject(project.getId().getProject());
					id.setPoSeries(series_no);
					id.setRevisionNo(0);
					id.setPoType(ConvertPoType(mmPurchase.getPoType()));
					id.setPoNo(document_no);
					model.setId(id);
				}
				//***************************************************************************************
				
				model.setTypeOfPurchase(mmPurchase.getPoType());
				model.setCreatedBy(mmPurchase.getCreatedBy());
				model.setPoDate(CommonService.ConvertStringToDateTime(mmPurchase.getPoDate()));
				model.setDepartmentCode(mmPurchase.getDepartmentCode());
				model.setCurrency(mmPurchase.getCurrency());
				model.setExchangeRate(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getExchangeRate())));						
				model.setVatBaseAmountLc(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getVatBaseAmountLc())));
				model.setDiscountAmountFc(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getDiscountAmountFc())));
				model.setVatAmountLc(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getVatAmountLc())));
				model.setNetAmountLc(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getNetAmountLc())));				
				model.setCreatedBy(mmPurchase.getCreatedBy());
				model.setCreatedOn(CommonService.ConvertStringToDateTime(mmPurchase.getCreatedOn()));				
				model.setLastUpdBy(mmPurchase.getUpdatedBy());
				model.setLastUpdOn(CommonService.ConvertStringToDateTime(mmPurchase.getUpdatedOn()));				
				model.setSyncExternalRefNo(mmPurchase.getExtRefNo());
				model.setSyncExternalRefKey(mmPurchase.getExtRefKey());
				model.setSyncIssync("Y");				
				model.setPaymentMode("1");				
				model.setDeliveryMode("ROAD");
				model.setTaxType(mmPurchase.getTaxType());
				model.setVatPercent(CommonService.ConvertStringToBigDecimal(mmPurchase.getVatPercent()));				
				model.setStatus(mmPurchase.getPoStatus());
				model.setSupplierCode(mmPurchase.getSupplierCode());				
				model.setVatIncludeFlag(mmPurchase.getVatIncludeFlag());
				
				return model;
			}
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}
		return null;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:40 PM 
	 * CreateBy=Chatree Siangklom
	 * BigDecimal
	 * TODO
	 * @param poHeader
	 * @param itemCode
	 * @return
	 * @throws Exception
	 */
	private BigDecimal FindPoSeq(PurchaseOrder poHeader, String itemCode) throws Exception {
		try{
			StringBuffer _strQuery = new StringBuffer();
			
			_strQuery.append(" Select PO_SEQ_NO,ITEM_CODE ");
			_strQuery.append(" From PURCHASE_ORDER_ITEMS ");
			_strQuery.append(" Where COMPANY = ").append("'" + poHeader.getId().getCompany() + "'");
			_strQuery.append(" AND PROJECT = ").append("'" + poHeader.getId().getProject() + "'");
			_strQuery.append(" AND PO_TYPE  = ").append("'" + poHeader.getId().getPoType() + "'");
			_strQuery.append(" AND PO_SERIES = ").append("'" + poHeader.getId().getPoSeries() + "'");
			_strQuery.append(" AND PO_NO =  ").append(poHeader.getId().getPoNo());
			_strQuery.append(" AND REVISION_NO = 0 ");
			_strQuery.append(" AND ITEM_CODE = '" + CommonService.IsNullRString(itemCode) + "' ");			
			log.info(CommonService.ReplaceStringToTxtDatabase(_strQuery.toString()));
			
			 List<Object[]> result = (List<Object[]>)EmPromis.createNativeQuery(_strQuery.toString()).getResultList();
			 if(!CommonService.IsNull(result)){
				 
				 if(result.size() > 1)
					 throw new Exception("PURCHASE_ORDER_ITEMS Mores then one Rec. ["+ CommonService.ReplaceStringToTxtDatabase(_strQuery.toString()) +"] ");
				 
				 for (Object[] resultElement : result) {					 
					 String PO_SEQ_NO = CommonService.IsNullRNull(resultElement[0]);  log.info("PO_SEQ_NO = " + PO_SEQ_NO);
					 return new BigDecimal(PO_SEQ_NO);
				 }
			 }else
				 return new BigDecimal("1");
			 
		}catch(Exception e){
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}
		return null;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:43 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param lst
	 * @throws Exception
	 */
	private void Validate(List<MmPurchaseOrder> lst) throws Exception {
		System.out.println("Start PO Validate Size=" + CommonService.getSize(lst));
		log.info("Start PO Validate Size=" + CommonService.getSize(lst));
		String company = null;
		String project = null;
		String buildingPhase = null;
		String zoneCode = null;
		String unit_number = null;
		String um = null;
		String taxType = null;
		
		try{
			if(!CommonService.IsNull(lst)){
				for(MmPurchaseOrder model : lst){
					
					//Company validate **********************************
					if(CommonService.IsNull(model.getSapCompanyCode())){					
						throw new Exception("Require field SAP Company Code !!!");
					}
					else
					{
						Company companySrv = new CompanyServices(EmPromis).findBySapCompany(model.getSapCompanyCode());
						if(CommonService.IsNull(companySrv)){
							throw new Exception("Data not found SAP Company [" + model.getSapCompanyCode()+"]");
						}else
							company = companySrv.getCompany();
					}
									
					if(CommonService.IsNull(model.getPoType()))
						throw new Exception("field POR_TYPE is require.");
					else{
						
						//C=Construction, S = Service
						//P=Promotion
						//A=Asset
						//M=Misc
						if(CommonService.IsNullRString(model.getPoType()).equals("C") 
								|| CommonService.IsNullRString(model.getPoType()).equals("S")
								|| CommonService.IsNullRString(model.getPoType()).equals("M")
								|| CommonService.IsNullRString(model.getPoType()).equals("A")
								|| CommonService.IsNullRString(model.getPoType()).equals("P")
						){}
							else
								throw new Exception("Data not found POR_TYPE ["+ model.getPoType() +"].");
					}
					
					//Plant validate **********************************
					if(CommonService.IsNull(model.getSapPlantCode())){
						throw new Exception("Require field plant !!!");
					}
					else
					{
						CostProject costProject = new ProjectServices(EmPromis).findByPlantCode(model.getSapPlantCode());
						if(CommonService.IsNull(costProject)){
							throw new Exception("Data not found CostProject SAP plant [" + model.getSapPlantCode()+"]");
						}else
							project = costProject.getId().getProject();
					}
			
					if(CommonService.IsNull(model.getItemCode()))
						throw new Exception("field ItemCode is require.");
					else {
						CostProjectArticlePK id = new CostProjectArticlePK();
						id.setCompany(company);
						id.setProject(project);
						id.setArticleCode(model.getItemCode());
						CostProjectArticle costProjectArticle = new CostProjectArticleServices(EmPromis).FindByKey(id);
						
						if(CommonService.IsNull(costProjectArticle))
							throw new Exception("Data not found Material ["+ model.getItemCode() +"].");
					}
					
					if(CommonService.IsNull(model.getItemUm()))
						throw new Exception("field Item Um is require.");
					else{
						UmMaster umObj = new UmMasterServices(EmPromis).findById(model.getItemUm());
						if(umObj != null)
							um = umObj.getUm();
						else
							throw new Exception("Data not found Item Um ["+ model.getItemUm() +"].");
					}
					
					if(CommonService.IsNull(model.getItemUmQty()))
						throw new Exception("field Item Um Qty is require.");
					
					if(CommonService.IsNull(model.getItemRate()))
						throw new Exception("field Item Um Rate is require.");
					
					if(CommonService.IsNull(model.getPoItemPrice()))
						throw new Exception("field PO Item Price is require.");
					
					if(CommonService.IsNull(model.getItemValueFc()))
						throw new Exception("field Item Value LC is require.");
					
					if(CommonService.IsNull(model.getPoDiscountAmount()))
						throw new Exception("field PO Discount Amount is require.");
					
					if(CommonService.IsNull(model.getDiscountAmount()))
						throw new Exception("field Discount Amount is require.");
					
					if(CommonService.IsNull(model.getPoNetItemPriceLc()))
						throw new Exception("field PO NetItemPriceLc is require.");
					
					if(CommonService.IsNull(model.getPoVatAmountLc()))
						throw new Exception("field PO Vat Amount LC is require.");
					
					if(CommonService.IsNull(model.getVatIncludeFlag()))
						throw new Exception("field Vat Include Flag is require.");
					
					if(CommonService.IsNull(model.getTaxType()))
						throw new Exception("field Tax Type is require.");
					else{
						
						TaxType taxTypeObj = new TaxTypeServices(EmPromis).findById(model.getTaxType());
						if(CommonService.IsNull(taxTypeObj)){
							throw new Exception("Data not found Tax Type ["+ model.getTaxType() +"].");
						}else
							taxType = taxTypeObj.getTaxType();
					}
					
					if(CommonService.IsNull(model.getPoLineStatus()))
						throw new Exception("field PO Line Status is require.");
					
					if(CommonService.IsNull(model.getCurrency()))
						throw new Exception("field Currency is require.");
					
					if(CommonService.IsNull(model.getVatBaseAmountLc()))
						throw new Exception("field Vat Base Amount LC is require.");
					
					if(CommonService.IsNull(model.getVatPercent()))
						throw new Exception("field Vat Persent is require.");
					
					if(CommonService.IsNull(model.getExchangeRate()))
						throw new Exception("field Exchange Rate is require.");
					
					if(CommonService.IsNull(model.getPoDeliveryDate()))
						throw new Exception("field PO Delivery Date is require.");
					
					if(CommonService.IsNull(model.getPrNo()))
						throw new Exception("field PR_NO is require.");
					else{
						SyncPr pr = new SyncPrServices(EmPromis).findByDocumentNo2(company, project, model.getPrNo());
						if(CommonService.IsNull(pr))
							throw new Exception("Data not found [company="+ company +" || project="+ project +" || PRDocuNo="+ model.getPrNo() +"].");
					}
					
					if(CommonService.IsNull(model.getRefPrLineSeq()))
						throw new Exception("field REF_PR_LINE_SEQ is require.");
					
					if(CommonService.IsNull(model.getExtRefKey()))
						throw new Exception("field SAP PO Key is require.");
					
					if(CommonService.IsNull(model.getExtRefNo()))
						throw new Exception("field SAP PO Number is require.");
					
					if(CommonService.IsNull(model.getPoDate()))
						throw new Exception("field PO_DATE is require.");
					
					if(CommonService.IsNull(model.getDepartmentCode()))
						throw new Exception("field DEPARTMENT_CODE is require.");
					
					if(CommonService.IsNull(model.getSeqNo()))
						throw new Exception("field SEQ_NO is require.");
					
					if(CommonService.IsNull(model.getPoStatus()))
						throw new Exception("field PO_STATUS is require.");
					else
					{
						if(CommonService.IsNullRString(model.getPoStatus()).equals("A") || CommonService.IsNullRString(model.getPoStatus()).equals("Z"))
						{}else{
							throw new Exception("Data not found SAP Company [" + model.getPoStatus()+"]");
						}
					}					
				}
			}else
				throw new Exception("MmPurchaseOrder is nothing size=" + CommonService.getSize(lst));
			
		}catch(Exception e){
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}finally
		{
			log.info("End of PO Validate --->");
			System.out.println("End of PO Validate --->");
		}
	}

	/**
	 * 
	 * Date =Nov 14, 2013 : 10:20:06 AM 
	 * CreateBy=Chatree Siangklom
	 * boolean
	 * TODO
	 * @param pr
	 * @param por_seq_no
	 * @return
	 * @throws Exception
	 */
	public boolean IsFullPRLineCumulativeQTY(SyncPr pr, MmPurchaseOrder mmPurchaseOrder) throws Exception {
		double prItemUmQty = 0;
		double prCumulativeQty = 0;
		try{
			
			if(CommonService.findString(pr.getDocumentNo(), "PR")){
				
				PurchaseRequestBudgetPK id = new PurchaseRequestBudgetPK();
				String company = pr.getCompany();
				String project = pr.getProject();
				String porType = pr.getPorType();
				String porSeries = pr.getPorSeries();
				long porNo = pr.getPorNo();						
				long seqNo = 	CommonService.ConvertStringToLong(mmPurchaseOrder.getRefPrLineSeq());			
				//long porSeqNo not set value for select 1 record. 
				
				log.info("company=" + company + "//project=" + project + "//porNo=" + porNo + "//porSeries=" + porSeries + "//porType=" + porType + "//seqNo=" + seqNo);
				
				id.setCompany(company);
				id.setProject(project);
				id.setPorNo(porNo);
				id.setPorSeries(porSeries);
				id.setPorType(porType);
				id.setSeqNo(seqNo);
				//id.setPorSeqNo(porSeqNo); //not set value
				
				PurchaseRequestBudget purchaseRequestBudget = new PurchaseRequestBudgetServices(EmPromis).findBy6Key(id);
				prItemUmQty = CommonService.ConvertBigDecimalToDouble(purchaseRequestBudget.getItemUmQty());
				prCumulativeQty = CommonService.ConvertBigDecimalToDouble(purchaseRequestBudget.getCumulativeQty());
				
			}else if(CommonService.findString(pr.getDocumentNo(), "PM")){
				PurchaseRequestItemPK id = new PurchaseRequestItemPK();
				
				String company = pr.getCompany();
				String project = pr.getProject();
				String porType = pr.getPorType();
				String porSeries = pr.getPorSeries();
				long porNo = pr.getPorNo();	
				long seqNo = 	CommonService.ConvertStringToLong(mmPurchaseOrder.getRefPrLineSeq());			
				
				id.setCompany(company);
				id.setProject(project);
				id.setPorType(porType);				
				id.setPorSeries(porSeries);
				id.setPorNo(porNo);
				id.setPorSeqNo(seqNo);

				PurchaseRequestItem purchaseRequestItem = new PurchaseRequestItemServices(EmPromis).findBy6Key(id);
				prItemUmQty = CommonService.ConvertBigDecimalToDouble(purchaseRequestItem.getItemUmQty());
				prCumulativeQty = CommonService.ConvertBigDecimalToDouble(purchaseRequestItem.getCumulativeQty());
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
			log.error(e.getMessage());
			throw new Exception("Error:" + e.getMessage());
		}
		
		return ((prItemUmQty - prCumulativeQty) > 0) ? false : true;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:41:50 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param MmPurchaseOrder_lst
	 * @throws Exception
	 */
	private void CreatedPO(List<MmPurchaseOrder> MmPurchaseOrder_lst)  throws Exception {		
		try{
					
			MmPurchaseOrderServices mmPurchaseOrderServ = new MmPurchaseOrderServices(EmSynchro);
			PurchaseOrder poHeader = null;
			List<PurchaseOrderBudget> itemBudget = new ArrayList<PurchaseOrderBudget>();
			List<PurchaseOrderItem> item = new ArrayList<PurchaseOrderItem>();
			
			try{
				//Validate is field
				Validate(MmPurchaseOrder_lst);
				
				if(!CommonService.IsNull(MmPurchaseOrder_lst))
				{
					PurchaseOrderServices purchaseOrderServ = new PurchaseOrderServices(EmPromis);
					SyncPrBudgetServices syncPrBudgetServ = new SyncPrBudgetServices(EmPromis);
					SyncPrItemServices syncPrItemServ = new SyncPrItemServices(EmPromis);
					List<PurchaseOrder> promis_po_list = new ArrayList<PurchaseOrder>();
					
					//Header
					MmPurchaseOrder mmPurchaseHeader = MmPurchaseOrder_lst.get(0);
					if(mmPurchaseHeader.getPrNo() != null)
					{					
						System.out.println("PromisStagingId : " + mmPurchaseHeader.getPromisStagingId() + "//InstanceNo : " + mmPurchaseHeader.getInstanceNo()  + " //SAP_Document_No : " + mmPurchaseHeader.getExtRefNo() + " //PROMIS PR No. : " + mmPurchaseHeader.getPrNo());
						log.info("PromisStagingId : " + mmPurchaseHeader.getPromisStagingId() + "//InstanceNo : " + mmPurchaseHeader.getInstanceNo()  + " //SAP_Document_No : " + mmPurchaseHeader.getExtRefNo() + " //PROMIS PR No. : " + mmPurchaseHeader.getPrNo());						
						
						poHeader = setHeader(mmPurchaseHeader);
						
						//purchaseOrderServ.CheckPoReceived(poId)
						for(MmPurchaseOrder mmPurchase : MmPurchaseOrder_lst)
						{	
							
							//Search PR Exists. ***************************************************************
							log.info("Search PR Exists. ***************************************************************");
							//SyncPr pr = new SyncPrServices(EmPromis).findByDocumentNo(poHeader.getId().getProject(), mmPurchase.getPrNo(), "A");
							SyncPr pr = new SyncPrServices(EmPromis).findByDocumentNo2(poHeader.getId().getCompany(), poHeader.getId().getProject(), mmPurchase.getPrNo());
							if(pr == null)
								throw new Exception("Error Data not found Purchase Request [Company="+ poHeader.getId().getCompany() + "|| Project=" + poHeader.getId().getProject() + "|| PR No="+ mmPurchase.getPrNo() + "|| SAP send type of purchase="+ mmPurchase.getPoType() +"] !!!");
							else
							{
								if((CommonService.IsNull(pr.getTypeOfPurchase()) || CommonService.IsNull(mmPurchase.getPoType())) && (CommonService.IsNullRString(pr.getTypeOfPurchase()).trim().toUpperCase() != CommonService.IsNullRString(mmPurchase.getPoType()).trim().toUpperCase()))
								{
									throw new Exception("Error Type of purchase not match PR, PO [Company=" + poHeader.getId().getCompany() 
																											+ "|| Project=" + poHeader.getId().getProject() 
																											+ "|| PrNo="+ mmPurchase.getPrNo() 
																											+ "|| Promis type of purchase=("+ pr.getTypeOfPurchase()+")" 
																											+" || Sap send type of purchase=("+ mmPurchase.getPoType() +")] !!!");
								}
							}
							
							/*
							 * Comment By DR.TREE 2013-01-30
							 * Change to Check by PR LINE
							if(CommonService.IsNullRString(pr.getStatus()).toUpperCase().equals("C"))
								throw new Exception("Purchase Request =["+ pr.getDocumentNo() +"] is fully.");
							*/
							
							if(CommonService.IsNullRString(pr.getStatus()).toUpperCase().equals("Z"))
								throw new Exception("Purchase Request =["+ pr.getDocumentNo() +"] is Canceled.");
							else if(CommonService.IsNullRString(pr.getStatus()).toUpperCase().equals("O"))
								throw new Exception("Purchase Request =["+ pr.getDocumentNo() +"] is Opened.");
							else if(CommonService.IsNullRString(pr.getStatus()).toUpperCase().equals("G"))
								throw new Exception("Purchase Request =["+ pr.getDocumentNo() +"] is Initial.");
							else if(CommonService.IsNullRString(pr.getStatus()).toUpperCase().equals("N"))
								throw new Exception("Purchase Request =["+ pr.getDocumentNo() +"] is Confirm.");
							
							/*
							 * please check qty by RP lineDR.TREE 2013-08-19 
							 * FUNCTION GET_PR_QTY_PENDING (
							IN_COMP ,
							IN_PROJECT ,
							IN_PR_TYPE ,
							IN_PR_SERIES ,
							IN_PR_NO ,
							IN_SEQ ,
							IN_ITEM_CODE ,
							IN_ITEM_UM ) RETURN NUMBER
							*/
							
							/*
							 * Kanchanaburi
							if(!CommonService.IsNullRString(pr.getStatus()).toUpperCase().equals("A"))
								throw new Exception("Purchase Request =["+ pr.getDocumentNo() +"] is not Approved."); 
							*/
							
							if(pr != null){
								log.info("Case PR :: Project="+ pr.getProject() +"  || PR DocumentNo=" + pr.getDocumentNo());
								System.out.println("Case PR :: Project="+ pr.getProject() +"  || PR DocumentNo=" + pr.getDocumentNo());
								
								if(CommonService.findString(pr.getDocumentNo(), "PR"))
								{
									//Set Budget
									PurchaseOrderBudgetPK id = new PurchaseOrderBudgetPK();
									id.setCompany(poHeader.getId().getCompany());
									id.setProject(poHeader.getId().getProject());
									id.setPoType(poHeader.getId().getPoType());
									id.setPoSeries(poHeader.getId().getPoSeries());
									id.setPoNo(poHeader.getId().getPoNo());
									id.setSeqNo(Long.parseLong(mmPurchase.getSeqNo().toString()));
									id.setRevisionNo(0);

									//find po seq no by Order Item
									BigDecimal poSeqNo = FindPoSeq(poHeader, mmPurchase.getItemCode());		//log.info("poSeqNo : " + poSeqNo);
									if(!CommonService.IsNull(poSeqNo))
										id.setPoSeqNo(Long.parseLong(poSeqNo.toString()));
																		
									PurchaseOrderBudgetServices PurchaseOrderBudgetServ = new PurchaseOrderBudgetServices(EmPromis);
									PurchaseOrderBudget orderBudget = PurchaseOrderBudgetServ.findById(id);
									
									if(orderBudget == null){
										System.out.println("Case PR :: Create New Order Budget --->"); 	log.info("Case PR :: Create New Order Budget --->");
										orderBudget = new PurchaseOrderBudget();
										orderBudget.setId(id);
									}else
										System.out.println("Case PR :: Update old Order Budget --->");		log.info("Case PR :: Update old Order Budget --->");
									
									orderBudget.setItemCode(mmPurchase.getItemCode());
									orderBudget.setItemDesc(mmPurchase.getItemDesc());
									orderBudget.setPoItemUm(mmPurchase.getItemUm());
									
									//Check PO Line Status
									if(CommonService.IsNullRString(mmPurchase.getPoLineStatus()).equals("A")){
										
										Double itemPoQty = Double.parseDouble(CommonService.IsNullRZero(mmPurchase.getItemUmQty()));  
										Double itemReceiptQty = Double.parseDouble(CommonService.IsNullRZero(orderBudget.getCumulativeQty())); 
										
										if(itemPoQty >= itemReceiptQty){
											orderBudget.setPoItemUmQty(new BigDecimal(CommonService.IsNullRZero(itemPoQty + "")));
											orderBudget.setPoLineStatus(mmPurchase.getPoLineStatus());
										}else{
											System.out.println("Case PR :: Can't Input QTY PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //UnitNumber = "+ orderBudget.getUnitNumber() + " //ItemCode = " +  orderBudget.getItemCode() +" //(PO Qty="+ itemPoQty +" < Recevied Qty="+ itemReceiptQty +")]");
											throw new Exception("Case PR :: Can't Input QTY PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //UnitNumber = "+ orderBudget.getUnitNumber() + " //ItemCode = " +  orderBudget.getItemCode() +" //(PO Qty="+ itemPoQty +" < Recevied Qty="+ itemReceiptQty +")]");
										}
									}else if(CommonService.IsNullRString(mmPurchase.getPoLineStatus()).equals("Z")){
										
										
										//Add By DR.TREE 
										//Add new Conditional Date 2013-11-14
										if(!CheckExist(poHeader.getSyncExternalRefNo())){
											boolean isPRLineFull = IsFullPRLineCumulativeQTY(pr, mmPurchase);
											if(isPRLineFull){
												throw new Exception("Validation error: Purchase Request line item is full !!!");
											}
										}
										
										
										Double itemNewPoQty = Double.parseDouble(CommonService.IsNullRZero(mmPurchase.getItemUmQty()));
										Double itemOldPoQty = Double.parseDouble(CommonService.IsNullRZero(orderBudget.getPoItemUmQty()));
										Double itemReceiptQty = Double.parseDouble(CommonService.IsNullRZero(orderBudget.getCumulativeQty()));
																				 
										if(itemOldPoQty > 0){
											//Au, User Purchase (P.AUM) SPL Confirm. 2013-02-01 (R#3303)
											//Comment : DR.TREE
											//if(itemOldPoQty == itemNewPoQty && itemReceiptQty <= 0){
											if(itemReceiptQty <= 0){
												orderBudget.setPoLineStatus(mmPurchase.getPoLineStatus());
											}else
											{
												System.out.println("Case PR :: Can't Cancel PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //UnitNumber = "+ orderBudget.getUnitNumber() + " //ItemCode = " +  orderBudget.getItemCode() +" //(OldPoQty="+ itemOldPoQty +" <> newPoQty="+ itemNewPoQty +" Or Received Qty > "+ itemReceiptQty +")]");
												throw new Exception("Case PR :: Can't Cancel PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //UnitNumber = "+ orderBudget.getUnitNumber() + " //ItemCode = " +  orderBudget.getItemCode() +" //(OldPoQty="+ itemOldPoQty +" <> newPoQty="+ itemNewPoQty +" Or Received Qty > "+ itemReceiptQty +")]");
											}
										}else{
											if(itemReceiptQty <= 0){
												orderBudget.setPoLineStatus(mmPurchase.getPoLineStatus());
											}else
											{
												System.out.println("Case PR :: Can't Cancel PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //UnitNumber = "+ orderBudget.getUnitNumber() + " //ItemCode = " +  orderBudget.getItemCode() +" //(Received Qty > "+ itemReceiptQty +")]");
												throw new Exception("Case PR :: Can't Cancel PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //UnitNumber = "+ orderBudget.getUnitNumber() + " //ItemCode = " +  orderBudget.getItemCode() +" //(Received Qty > "+ itemReceiptQty +")]");
											}
										}
									}else{
										System.out.println("Case PR :: Not Found Status :: PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //UnitNumber = "+ orderBudget.getUnitNumber() + " //ItemCode = " +  orderBudget.getItemCode() +" ]");
										throw new Exception("Case PR :: Not Found Status :: PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //UnitNumber = "+ orderBudget.getUnitNumber() + " //ItemCode = " +  orderBudget.getItemCode() +" ]");
									}
									
									/*
									 * Comment DR.TREE 2013-01-30
									if(!CommonService.IsNull(mmPurchase.getItemUmQty()))
										orderBudget.setPoItemUmQty(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemUmQty())));
									*/
									
									if(!CommonService.IsNull(mmPurchase.getItemValueFc()))
									{
										orderBudget.setPoNetValueLc(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemValueFc())));
										//orderBudget.setItemValueFc(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemValueFc())));
									}
									
									if(!CommonService.IsNull(mmPurchase.getItemRate()))
									{
										orderBudget.setPoItemRate(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemRate())));
										//orderBudget.setItemRate(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemRate())));
									}
									
									orderBudget.setRequiredByDate(CommonService.ConvertStringToDateTime(mmPurchase.getPoDeliveryDate()));
									
									//Amnart need for cancel qty after GP out BOQ.
									orderBudget.setAdjustFlag(mmPurchase.getAdjustFlag());
									
									//Amnart need for cancel qty after GP out BOQ.
									orderBudget.setAdjustPoQty(CommonService.ConvertStringToBigDecimal(mmPurchase.getAdjustPoQty()));																	
									
									/*
									 * Commnet By : DR.TREE 2013-01-30
									if(CommonService.IsNullRString(mmPurchase.getPoLineStatus()).equals("Z")){
										if(Double.parseDouble(CommonService.IsNullRZero(orderBudget.getCumulativeQty())) <= 0)
											//Po line Status [A=Approved, Z= Cancel]
											orderBudget.setPoLineStatus("Z");
										else
											throw new Exception("Can't Cancel PO Line Item  [UnitNumber = "+ orderBudget.getUnitNumber() + " // ItemCode = " +  orderBudget.getItemCode() +" // Recevied Qty = "+ orderBudget.getCumulativeQty() +"] ");
									}else
										orderBudget.setPoLineStatus(mmPurchase.getPoLineStatus());
									*/
									
									String [] pr_document_no = deDocument(mmPurchase.getPrNo());
									if(pr_document_no != null && pr_document_no.length > 0)
									{
										orderBudget.setPorType(pr_document_no[0]);
										orderBudget.setPorSeries(pr_document_no[1]);
										
										if(pr_document_no[2] != null)
											orderBudget.setPorNo(new BigDecimal(pr_document_no[2].toString()));
										
										if(!CommonService.IsNull(mmPurchase.getRefPrLineSeq()))
											orderBudget.setPorSeq(new BigDecimal(mmPurchase.getRefPrLineSeq()));
									}
									
									if(!CommonService.IsNull(mmPurchase.getPoItemPrice()))
										orderBudget.setPoItemPrice(new BigDecimal(mmPurchase.getPoItemPrice()));
									
									if(!CommonService.IsNull(mmPurchase.getPoDiscountAmount()))
										orderBudget.setPoDicountAmount(new BigDecimal(mmPurchase.getPoDiscountAmount()).abs());
									
									if(!CommonService.IsNull(mmPurchase.getPoNetItemPriceLc()))
										orderBudget.setPoNetItemPriceLc(new BigDecimal(mmPurchase.getPoNetItemPriceLc()));
									
									if(!CommonService.IsNull(mmPurchase.getPoVatAmountLc()))
										orderBudget.setPoVatAmountLc(new BigDecimal(mmPurchase.getPoVatAmountLc()));							
									
									orderBudget.setCreatedOn(poHeader.getCreatedOn());
									orderBudget.setCreatedBy(poHeader.getCreatedBy());									
									orderBudget.setLastUpdOn(poHeader.getLastUpdOn());
									orderBudget.setLastUpdBy(poHeader.getLastUpdBy());
									
									orderBudget.setSyncExternalRefKey(poHeader.getSyncExternalRefKey());
									orderBudget.setSyncExternalRefNo(poHeader.getSyncExternalRefNo());									
									orderBudget.setStatus(poHeader.getStatus());
									
									//PR							
									SyncPrBudget prBudget = syncPrBudgetServ.findByPrDocument(orderBudget.getId().getCompany(), orderBudget.getId().getProject(), mmPurchase.getPrNo(), Integer.parseInt(mmPurchase.getRefPrLineSeq()));
									if(prBudget != null)
									{
										orderBudget.setItemUm(prBudget.getItemUm());
										orderBudget.setBuildingPhase(prBudget.getBuildingPhase());
										orderBudget.setUnitNumber(prBudget.getUnitNumber());
										orderBudget.setZoneCode(prBudget.getZoneCode());								
										orderBudget.setRequiredByDate(prBudget.getRequiredByDate());	
										
										
										//Check 
									}
									itemBudget.add(orderBudget);
									
								}else if(CommonService.findString(pr.getDocumentNo(), "PM"))
								{
									//Set Item
									PurchaseOrderItemPK id = new PurchaseOrderItemPK();
									id.setCompany(poHeader.getId().getCompany());
									id.setProject(poHeader.getId().getProject());
									id.setPoType(poHeader.getId().getPoType());
									id.setPoSeries(poHeader.getId().getPoSeries());
									id.setPoNo(poHeader.getId().getPoNo());
									
									//id.setPoSeqNo(Long.parseLong(irow + ""));
									id.setPoSeqNo(Long.parseLong(mmPurchase.getSeqNo().toString()));
									id.setRevisionNo(0);
									
									PurchaseOrderItemServices PurchaseOrderItemServ = new PurchaseOrderItemServices(EmPromis);
									PurchaseOrderItem orderItem = PurchaseOrderItemServ.findById(id);
									
									if(CommonService.IsNull(orderItem))
									{
										//New Order Item
										log.info("Case PM :: Create New Order Item --->");
										System.out.println("Case PM :: Create New Order Item --->");
										orderItem = new PurchaseOrderItem();
										orderItem.setId(id);
									}					
									else{
										log.info("Case PM :: Update old Order Budget --->");
										System.out.println("Case PM :: Update old Order Budget --->");
									}
																			
									orderItem.setItemCode(mmPurchase.getItemCode());
									orderItem.setArtDesc(mmPurchase.getItemDesc());
									orderItem.setPoItemUm(mmPurchase.getItemUm());
									
									//Check PO Line Status
									if(CommonService.IsNullRString(mmPurchase.getPoLineStatus()).equals("A")){
										
										
										//Add By DR.TREE 
										//Add new Conditional Date 2013-11-14
										if(!CheckExist(poHeader.getSyncExternalRefNo())){
											boolean isPRLineFull = IsFullPRLineCumulativeQTY(pr, mmPurchase);
											if(isPRLineFull){
												throw new Exception("Validation error: Purchase Request line item is full !!!");
											}
										}
										
										
										Double itemPoQty = Double.parseDouble(CommonService.IsNullRZero(mmPurchase.getItemUmQty()));
										Double itemReceiptQty = Double.parseDouble(CommonService.IsNullRZero(orderItem.getRcvdQty()));
										if(itemPoQty >= itemReceiptQty){
											orderItem.setPoItemUmQty(new BigDecimal(CommonService.IsNullRZero(itemPoQty+"")));
											orderItem.setPoLineStatus(mmPurchase.getPoLineStatus());
										}											
										else{
											System.out.println("Case PM :: Can't Input QTY PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //ItemCode = " +  orderItem.getItemCode() +" //(PO Qty="+ itemPoQty +" < Recevied Qty="+ itemReceiptQty +")]");
											throw new Exception("Case PM :: Can't Input QTY PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //ItemCode = " +  orderItem.getItemCode() +" //(PO Qty="+ itemPoQty +" < Recevied Qty="+ itemReceiptQty +")]");
										}
									}else if(CommonService.IsNullRString(mmPurchase.getPoLineStatus()).equals("Z")){
										Double itemNewPoQty = Double.parseDouble(CommonService.IsNullRZero(mmPurchase.getItemUmQty()));
										Double itemOldPoQty = Double.parseDouble(CommonService.IsNullRZero(orderItem.getPoItemUmQty()));
										Double itemReceiptQty = Double.parseDouble(CommonService.IsNullRZero(orderItem.getRcvdQty()));
																				
										if(itemOldPoQty > 0){
											//Au, User Purchase SPL Confirm. 2013-02-01 (R#3303)
											//Comment : DR.TREE 
											//if(itemOldPoQty == itemNewPoQty && itemReceiptQty <= 0){
											if(itemReceiptQty <= 0){
												orderItem.setPoLineStatus(mmPurchase.getPoLineStatus());
											}else
											{
												System.out.println("Case PM :: Can't Cancel PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //ItemCode = " +  orderItem.getItemCode() +" //(OldPoQty="+ itemOldPoQty +" <> newPoQty="+ itemNewPoQty +" Or Received Qty > "+ itemReceiptQty +")]");
												throw new Exception("Case PM :: Can't Cancel PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //ItemCode = " +  orderItem.getItemCode() +" //(OldPoQty="+ itemOldPoQty +" <> newPoQty="+ itemNewPoQty +" Or Received Qty > "+ itemReceiptQty +")]");
											}	
										}else{
											if(itemReceiptQty <= 0){
												orderItem.setPoLineStatus(mmPurchase.getPoLineStatus());
											}else
											{
												System.out.println("Case PM :: Can't Cancel PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //ItemCode = " +  orderItem.getItemCode() +" //(Received Qty > "+ itemReceiptQty +")]");
												throw new Exception("Case PM :: Can't Cancel PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //ItemCode = " +  orderItem.getItemCode() +" //(Received Qty > "+ itemReceiptQty +")]");
											}
										}
									}else{
										System.out.println("Case PM :: Not Found Status :: PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //ItemCode = " +  orderItem.getItemCode() +" ]");
										throw new Exception("Case PM :: Not Found Status :: PO Line Item [PO Seq = "+ mmPurchase.getSeqNo() +" //ItemCode = " +  orderItem.getItemCode() +" ]");
									}
									
									/*
									 * Commnet By : DR.TREE 2013-01-30
									if(!CommonService.IsNull(mmPurchase.getItemUmQty()))
										orderItem.setPoItemUmQty(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemUmQty())));
									*/
									
									if(!CommonService.IsNull(mmPurchase.getItemValueFc())){
										//orderItem.setItemValueFc(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemValueFc()))); //P'Ta can your Calculate.
										orderItem.setPoNetValueLc(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemValueFc())));
									}
									
									if(!CommonService.IsNull(mmPurchase.getItemRate()))
										//orderItem.setItemRate(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemRate())));
										orderItem.setPoItemRate(new BigDecimal(CommonService.IsNullRZero(mmPurchase.getItemRate())));
									
									//Ref PR
									String [] pr_document_no = deDocument(mmPurchase.getPrNo());
									if(pr_document_no != null && pr_document_no.length > 0)
									{
										orderItem.setPorType(pr_document_no[0]);
										orderItem.setPorSeries(pr_document_no[1]);
										
										if(pr_document_no[2] != null)
											orderItem.setPorNo(new BigDecimal(pr_document_no[2].toString()));
										
										if(!CommonService.IsNull(mmPurchase.getRefPrLineSeq()))
											orderItem.setPorSeqNo(new BigDecimal(mmPurchase.getRefPrLineSeq()));
									}
									
									orderItem.setRequiredByDate(CommonService.ConvertStringToDateTime(mmPurchase.getPoDeliveryDate()));
									
									//Amnart need for cancel qty after GP out BOQ.
									orderItem.setAdjustFlag(mmPurchase.getAdjustFlag());
									
									//Amnart need for cancel qty after GP out BOQ.
									orderItem.setAdjustPoQty(CommonService.ConvertStringToBigDecimal(mmPurchase.getAdjustPoQty()));														
									
									/*
									 * Commnet By : 2013-01-30
									if(CommonService.IsNullRString(mmPurchase.getPoLineStatus()).equals("Z")){
										if(Double.parseDouble(CommonService.IsNullRZero(orderItem.getRcvdQty())) <= 0)
											//Po line Status [A=Approved, Z= Cancel]
											orderItem.setPoLineStatus("Z");
										else
											throw new Exception("Can't Cancel PO Line Item [ItemCode = " +  orderItem.getItemCode() +" //Recevied Qty = "+ orderItem.getRcvdQty() +" ]");
									}else
										orderItem.setPoLineStatus(mmPurchase.getPoLineStatus());
									*/
									
									if(!CommonService.IsNull(mmPurchase.getPoItemPrice()))
										orderItem.setPoItemPrice (new BigDecimal(mmPurchase.getPoItemPrice()));
									
									if(!CommonService.IsNull(mmPurchase.getPoDiscountAmount()))
										orderItem.setPoDicountAmount(new BigDecimal(mmPurchase.getPoDiscountAmount()));
									
									if(!CommonService.IsNull(mmPurchase.getPoNetItemPriceLc()))
										orderItem.setPoNetItemPriceLc(new BigDecimal(mmPurchase.getPoNetItemPriceLc()));
									
									if(!CommonService.IsNull(mmPurchase.getPoVatAmountLc()))
										orderItem.setPoVatAmountLc(new BigDecimal(mmPurchase.getPoVatAmountLc()));							
									
									orderItem.setCreatedOn(poHeader.getCreatedOn());
									orderItem.setCreatedBy(poHeader.getCreatedBy());									
									orderItem.setLastUpdOn(poHeader.getLastUpdOn());
									orderItem.setLastUpdBy(poHeader.getLastUpdBy());
									
									orderItem.setSyncExternalRefKey(poHeader.getSyncExternalRefKey());
									orderItem.setSyncExternalRefNo(poHeader.getSyncExternalRefNo());									
									orderItem.setStatus(poHeader.getStatus());
									
									//PM							
									SyncPrItem prItem = syncPrItemServ.findByPrDocument(orderItem.getId().getCompany(), orderItem.getId().getProject(), mmPurchase.getPrNo(), Integer.parseInt(mmPurchase.getRefPrLineSeq()));
									if(prItem != null)
									{
										orderItem.setItemUm(prItem.getItemUm());
										orderItem.setRequiredByDate(prItem.getRequiredByDate());
										
										if((CommonService.IsNull(prItem.getTypeOfPurchase()) || CommonService.IsNull(mmPurchase.getPoType())) && (CommonService.IsNullRString(prItem.getTypeOfPurchase()).trim().toUpperCase() != CommonService.IsNullRString(mmPurchase.getPoType()).trim().toUpperCase()))
										{
											throw new Exception("ERROR Type of purchase not match PR, PO [Company=" + orderItem.getId().getCompany() 
																													+ "|| Project=" + orderItem.getId().getProject() 
																													+ "|| PrNo="+ mmPurchase.getPrNo() 
																													+ "|| promis type of purchase=("+ pr.getTypeOfPurchase()+")" 
																													+" || sap send type of purchase=("+ mmPurchase.getPoType() +")] !!!");
										}
									}else{
										throw new Exception("ERROR Data not found PR [Company="+ orderItem.getId().getCompany() + "|| Project=" + orderItem.getId().getProject() + "|| PrNo="+ mmPurchase.getPrNo() + "|| RefPrLineSeq="+ Integer.parseInt(mmPurchase.getRefPrLineSeq()) +"] !!!");
									}
									
									item.add(orderItem);
								}
							}
						}				
						promis_po_list.add(poHeader);
												
						//---------------------------------------------------------------------------------------------------------------------------------
						System.out.println("poHeader getSyncExternalRefNo=" + poHeader.getSyncExternalRefNo() + " //item size=" + CommonService.getSize(item) + " //itemBudget size=" + CommonService.getSize(itemBudget));		
						log.info("poHeader getSyncExternalRefNo=" + poHeader.getSyncExternalRefNo() + " //item size=" + CommonService.getSize(item) + " //itemBudget size=" + CommonService.getSize(itemBudget));
						
						if(!CheckExist(poHeader.getSyncExternalRefNo())){
							//INSERT PO
							purchaseOrderServ.Inserted(poHeader, item, itemBudget);
						}
						else if(CheckExist(poHeader.getSyncExternalRefNo())){
							//UPDATE PO
							purchaseOrderServ.Updated(poHeader, item, itemBudget);
						}else
							throw new Exception("Can't Create or Update SAP PO=" + poHeader.getSyncExternalRefNo() + " || Item length=" + CommonService.getSize(item) + " || Item Budget=" + CommonService.getSize(itemBudget));
						
						
						if(poHeader.getId() == null || CommonService.IsNull(poHeader.getId().getPoSeries())){
							throw new Exception("Error PROMIS PO Header is null MmPurchaseOrder_lenght="+ CommonService.getSize(MmPurchaseOrder_lst) +" || Item length=" + CommonService.getSize(item) + " || Item Budget=" + CommonService.getSize(itemBudget));
						}
						
						//UPDATE IS SYNC = Y
						List<MmPurchaseOrder> poSyncLst = new ArrayList<MmPurchaseOrder>();
						for(MmPurchaseOrder mmPurchase : MmPurchaseOrder_lst)
						{
							mmPurchase.setRetuPmsPoCompany(poHeader.getId().getCompany());
							mmPurchase.setRetuPmsPoProject(poHeader.getId().getProject());
							mmPurchase.setRetuPmsPoType(poHeader.getId().getPoType());
							mmPurchase.setRetuPmsPoSeries(poHeader.getId().getPoSeries());
							mmPurchase.setRetuPmsPoNo(poHeader.getId().getPoNo());
							mmPurchase.setRetuPmsPoRevisionNo(poHeader.getId().getRevisionNo());							
							mmPurchase.setRetuPmsPoPoDocNo( CommonService.IsNullRString(poHeader.getId().getPoType()) + "-" 
														  + CommonService.IsNullRString(poHeader.getId().getPoSeries()) + "-" 
														  + Utilitys.leftPad(CommonService.IsNullRString(poHeader.getId().getPoNo()), 6, "0") + "-" 
														  + CommonService.IsNullRString(poHeader.getId().getRevisionNo()));
							
							mmPurchase.setIssync("Y");
							mmPurchase.setMsgCode("S");
							mmPurchase.setMsgDesc("Success");
							mmPurchase.setMsgActResult(null);
							poSyncLst.add(mmPurchase);
						}
						new MmPurchaseOrderServices(EmSynchro).Updated(poSyncLst);
						//---------------------------------------------------------------------------------------------------------------------------------
					}
				}
			}catch(Exception ex)
			{
				System.out.println(ex.getMessage());
				log.error(ex.getMessage());
				
				if(!CommonService.IsNull(MmPurchaseOrder_lst))
				{
					List<MmPurchaseOrder> poSyncLst = new ArrayList<MmPurchaseOrder>();
					for(MmPurchaseOrder mmPurchase : MmPurchaseOrder_lst)
					{
						mmPurchase.setIssync("N");
						mmPurchase.setMsgCode("E");
						mmPurchase.setMsgDesc(CommonService.CutString(ex.getMessage(), 3500));
						mmPurchase.setMsgActResult(CommonService.CutString(ex.getMessage(), 3500));
						poSyncLst.add(mmPurchase);
					}
					mmPurchaseOrderServ.Updated(poSyncLst);
				}
				throw ex;
			}
		}catch(Exception e)
		{			
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:42:01 PM 
	 * CreateBy=Chatree Siangklom
	 * String[]
	 * TODO
	 * @param pr_document_no
	 * @return
	 * @throws Exception
	 */
	private String[] deDocument(String pr_document_no) throws Exception
	{
		if(!CommonService.IsNull(pr_document_no)){
			String [] temp = pr_document_no.split("\\-");
			return temp;
		}else
			return null;
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:42:04 PM 
	 * CreateBy=Chatree Siangklom
	 * List<MmPurchaseOrderGroupSearch>
	 * TODO
	 * @param sap_po_no
	 * @param instanceNo
	 * @return
	 * @throws Exception
	 */
	private List<MmPurchaseOrderGroupSearch> SearchMmPurchaseGroupBy(String sap_po_no, String instanceNo)  throws Exception 
	{
		try
		{
			List<Object[]> result = (List<Object[]>)EmSynchro.createNativeQuery(" SELECT A.INSTANCE_NO, A.EXT_REF_NO,A.PO_STATUS FROM MM_PURCHASE_ORDERS A  WHERE A.INSTANCE_NO = '" + CommonService.IsNullRString(instanceNo) + "' AND A.EXT_REF_NO = '"+ CommonService.IsNullRString(sap_po_no) +"' GROUP BY A.INSTANCE_NO, A.EXT_REF_NO,A.PO_STATUS ORDER BY A.INSTANCE_NO asc ").getResultList();

			 List<MmPurchaseOrderGroupSearch> lst = new ArrayList<MmPurchaseOrderGroupSearch>();
			 if(!CommonService.IsNull(result)){
				 
				 for (Object[] resultElement : result) {
					 String INSTANCE_NO = CommonService.IsNullRString(resultElement[0]);
					 String EXT_REF_NO = CommonService.IsNullRString(resultElement[1]);
					 String PO_STATUS = CommonService.IsNullRString(resultElement[2]);				 
					 lst.add(new MmPurchaseOrderGroupSearch(INSTANCE_NO, EXT_REF_NO, PO_STATUS));
				 }
			 }
			 return lst;
			
		}catch(Exception e){
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:42:09 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param sap_po_document_no
	 * @param instanceNo
	 * @throws Exception
	 */
	public void CreateToPromis(String sap_po_document_no, String instanceNo) throws Exception{
		System.out.println("Start CreateToPromis sap_po_document_no = " + sap_po_document_no + " //instanceNo = " + instanceNo);
		log.info("Start CreateToPromis sap_po_document_no = " + sap_po_document_no + " //instanceNo = " + instanceNo);
		try{
			
			if(!CommonService.IsNull(sap_po_document_no)){				
				PurchaseOrderAction obj = new PurchaseOrderAction();
				List<String> po_list = null;
				
				//po_list = obj.GroupSAPPoDoc();
				
				po_list = new ArrayList<String>();
				po_list.add(sap_po_document_no);
				
				
				for(String sap_no : po_list){
					String sap_po_no = sap_no; //"1410000025";
					List<MmPurchaseOrderGroupSearch> lst = obj.SearchMmPurchaseGroupBy(sap_po_no, instanceNo);					
					System.out.println("SearchMmPurchaseGroupBy list : " + CommonService.getSize(lst));
					
					List<MmPurchaseOrder> MmPurchaseOrder_lst = null;
					for(MmPurchaseOrderGroupSearch mmPo : lst)
					{
						System.out.println("InstanceNo=" + mmPo.getInstanceNo() + " || SAP_PO_NO=" + mmPo.getExtRefNo() + " || PoStatus=" + mmPo.getPoStatus());
						log.info("InstanceNo=" + mmPo.getInstanceNo() + " || SAP_PO_NO=" + mmPo.getExtRefNo() + " || PoStatus=" + mmPo.getPoStatus());
						
						//Cancel PO
						if(mmPo.getPoStatus().equals("Z")){
							System.out.println("Start Cancel PO ---> ");
							log.info("Start Cancel PO ---> ");
							MmPurchaseOrder_lst = obj.findSapPoDoc("N", mmPo.getInstanceNo(), mmPo.getExtRefNo(), mmPo.getPoStatus());
							if(!CommonService.IsNull(MmPurchaseOrder_lst)){				
								
								MmPurchaseOrder mPurchaseOrder = MmPurchaseOrder_lst.get(0);
								System.out.println("Cancel PO  getPromisStagingId : " + mPurchaseOrder.getPromisStagingId() + " || SAP_PO_NO : " + mPurchaseOrder.getExtRefNo());
								log.info("Cancel PO  getPromisStagingId : " + mPurchaseOrder.getPromisStagingId() + " || SAP_PO_NO : " + mPurchaseOrder.getExtRefNo());
								try{
									
									log.info("Is Cancel PO " + obj.CanclePo(MmPurchaseOrder_lst));
									
								}catch(Exception e){
									
									List<MmPurchaseOrder> poSyncLst = new ArrayList<MmPurchaseOrder>();
									for(MmPurchaseOrder mmPurchase : MmPurchaseOrder_lst)
									{
										mmPurchase.setIssync("Y");
										mmPurchase.setMsgCode("E");
										mmPurchase.setMsgDesc(CommonService.CutString(e.getMessage(), 3500));
										mmPurchase.setMsgAltDesc(CommonService.CutString(e.getMessage(), 3500));
										mmPurchase.setMsgActResult(null);										
										poSyncLst.add(mmPurchase);
									}
									
									new MmPurchaseOrderServices(EmSynchro).Updated(poSyncLst);
									
									throw e;
								}
							}
						}else if(mmPo.getPoStatus().equals("A")){
							
							//Create PO
							System.out.println("Start Created PO ---> ");
							log.info("Start Created PO ---> ");
							MmPurchaseOrder_lst = obj.findSapPoDoc("N", mmPo.getInstanceNo(), mmPo.getExtRefNo(), mmPo.getPoStatus());
							if(!CommonService.IsNull(MmPurchaseOrder_lst)){
								MmPurchaseOrder mPurchaseOrder = MmPurchaseOrder_lst.get(0);
								
								obj.CreatedPO(MmPurchaseOrder_lst);
								
								System.out.println("Created PO  getPromisStagingId : " + mPurchaseOrder.getPromisStagingId() + " SAP_PO_NO : " + mPurchaseOrder.getExtRefNo());
								log.info("Created PO  getPromisStagingId : " + mPurchaseOrder.getPromisStagingId() + " SAP_PO_NO : " + mPurchaseOrder.getExtRefNo());								
							}
						}				
					}
				}
			}else {
				System.out.println("No sap_po_document_no !!!");
				throw new Exception("No sap_po_document_no !!!");
			}
		}catch(Exception e){
			System.out.println(e.getMessage());
			log.error(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:42:12 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @throws Exception
	 */
	@Deprecated
	private void start() throws Exception 
	{
		try
		{
			PurchaseOrderAction obj = new PurchaseOrderAction(); 			
			List<String> po_list = obj.GroupSAPPoDoc();
			
			po_list = new ArrayList<String>();
			po_list.add("1410003189");
			String instanceNo ="10000000000002016263";

			for(String sap_no : po_list){
				
				String sap_po_no = sap_no; //"1410000025";
				
				log.info("sap_no = " + sap_no);
				
				List<MmPurchaseOrderGroupSearch> lst = obj.SearchMmPurchaseGroupBy(sap_po_no, instanceNo);
				List<MmPurchaseOrder> MmPurchaseOrder_lst = null;
				for(MmPurchaseOrderGroupSearch mmPo : lst)
				{
					log.info("InstanceNo : " + mmPo.getInstanceNo() + " SAP_PO_NO : " + mmPo.getExtRefNo() + " PoStatus : " + mmPo.getPoStatus());
					
					//Cancel PO
					if(mmPo.getPoStatus().equals("Z")){
						System.out.println("Start Cancel PO --------------------------------------------> ");
						log.info("Start Cancel PO --------------------------------------------> ");
						MmPurchaseOrder_lst = obj.findSapPoDoc("N", mmPo.getInstanceNo(), mmPo.getExtRefNo(), mmPo.getPoStatus());
						System.out.println("MmPurchaseOrder_lst.size : " + CommonService.getSize(MmPurchaseOrder_lst));
						log.info("MmPurchaseOrder_lst.size : " + CommonService.getSize(MmPurchaseOrder_lst));
						if(!CommonService.IsNull(MmPurchaseOrder_lst)){				
							
							MmPurchaseOrder mPurchaseOrder = MmPurchaseOrder_lst.get(0);						
							log.info("Cancel PO PromisStagingId : " + mPurchaseOrder.getPromisStagingId() + " SAP_PO_NO : " + mPurchaseOrder.getExtRefNo());
							log.info("Is Cancel PO " + obj.CanclePo(MmPurchaseOrder_lst));
							
						}
					}else if(mmPo.getPoStatus().equals("A")){
						
						//Create PO
						System.out.println("Start Created PO --------------------------------------------> ");
						log.info("Start Created PO --------------------------------------------> ");
						MmPurchaseOrder_lst = obj.findSapPoDoc("N", mmPo.getInstanceNo(), mmPo.getExtRefNo(), mmPo.getPoStatus());
						if(!CommonService.IsNull(MmPurchaseOrder_lst)){
							
							MmPurchaseOrder mPurchaseOrder = MmPurchaseOrder_lst.get(0);
							System.out.println("Created PO  PromisStagingId : " + mPurchaseOrder.getPromisStagingId() + " SAP_PO_NO : " + mPurchaseOrder.getExtRefNo());
							log.info("Created PO  PromisStagingId : " + mPurchaseOrder.getPromisStagingId() + " SAP_PO_NO : " + mPurchaseOrder.getExtRefNo());
							obj.CreatedPO(MmPurchaseOrder_lst);
							
						}
					}				
				}
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
			System.out.println(ex.getMessage());
			log.error(ex.getMessage());
			throw ex;
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:42:16 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @throws Exception
	 */
	public void RunAll() throws Exception {
		try{
			StringBuilder _strQuery = new StringBuilder();
			_strQuery.append(" Select EXT_REF_NO, INSTANCE_NO,PO_STATUS,ISSYNC ");
			_strQuery.append(" From SYNCHRO.MM_PURCHASE_ORDERS  ");
			_strQuery.append(" Where NVL(MSG_CODE,'E') = 'E' And  ISSYNC = 'N' ");
			_strQuery.append(" Group by EXT_REF_NO, INSTANCE_NO, PO_STATUS, ISSYNC ");
			_strQuery.append(" Order By EXT_REF_NO ASC, INSTANCE_NO ASC  ");
			
			List<Object[]> result = (List<Object[]>)EmSynchro.createNativeQuery(_strQuery.toString()).getResultList();
			 if(!CommonService.IsNull(result)){
				try{
					
					for (Object[] value : result) {					 
						 String sap_po_document_no = CommonService.IsNullRNull(value[0]);
						 String instanceNo = CommonService.IsNullRNull(value[1]);
						 try{
							 new PurchaseOrderAction().CreateToPromis(sap_po_document_no, instanceNo);
						 }catch(Exception e){
							 System.out.println(e.getMessage());
							 log.error(e.getMessage());							 
						 }
					 }
					
				}catch(Exception e){
					e.printStackTrace();
					System.out.println(e.getMessage());
					log.error(e.getMessage());
				}
			 }
		}catch(Exception e){
			e.printStackTrace();
			System.out.println(e.getMessage());
			log.error(e.getMessage());
		}
	}
	
	/**
	 * 
	 * Date =Nov 13, 2013 : 2:42:19 PM 
	 * CreateBy=Chatree Siangklom
	 * void
	 * TODO
	 * @param args
	 */
	public static void main(String []args)
	{
		try{
			new PurchaseOrderAction().start();
			
		}catch(Exception e)
		{
			e.printStackTrace();
			log.error(e.getMessage());
			System.out.println(e.getMessage());
		}
	}
}